 /*
 * 产品分类管理视图
 * @Author: LuoQianJun
 * @Date: 2018-01-25 15:36:18
 * @Last Modified by: LuoQianJun
 * @Last Modified time: 2018-02-09 11:38:35
 */

<style lang="less" rel="stylesheet/less" type="text/less" scoped>

    .v-admin-product-category-views {
        padding: 20px;
    }

</style>

 <template>

    <div class="v-admin-product-category-views">

        <!-- 面包屑组件 -->
        <vBreadcrumb :breadcrumbList="breadcrumbList"></vBreadcrumb>

        <Tabs type="card" @on-click="changeTab">

            <TabPane label="新增" name="新增">
                
                <category-create ref="create"
                            :super-categories="super_categories"
                            @post="postData">
                </category-create>


            </TabPane>


            <TabPane label="查看" name="查看">

                <!-- 搜索组件 -->
                <!-- <search-form  @search="confirmSearch"></search-form> -->
                
                <category-index :loading="table_loading"
                                :product-categories="product_categories.data" 
                                :super-categories="super_categories"
                                @edit="getCategoryDetail" 
                                @delete="deleteCategory">                       
                </category-index>
                <br>  



                <!-- 分页组件 -->
                <Row type="flex" justify="center">
                    <Page @on-change="pageChange" 
                        @on-page-size-change="perPageChange"
                        placement="top"
                        :total="product_categories.total"
                        :current="product_categories.current_page"
                        :page-size="query_info.per_page"
                        show-sizer show-total></Page>
                </Row>

            
            </TabPane>
        </Tabs>

        <Modal title="修改产品分类" v-model="show_modal">
            
            <!-- 产品分类编辑组件 -->
            <category-edit  :category-detail="category_detail"
                            :super-categories="super_categories"
                            @update="updateCategory"
                            ></category-edit>           
                                                    

            <div slot="footer"></div>

        </Modal>

    </div>

 </template>
 
 <script>

import API_LIST from 'src/API_LIST';

import vBreadcrumb from 'src/views/component/breadcrumb';

import { mapGetters , mapMutations } from "vuex";

import qs from 'qs';

import categoryCreate from './create';

import categoryIndex from './index';

import categoryEdit from './edit';

// import searchForm from './search-form';

 export default {

     name: 'product-category',

      components : {

        vBreadcrumb,

        categoryCreate,

        categoryIndex,

        categoryEdit,

        // searchForm
    
    },

    data: function() {	

         return {

            breadcrumbList: [
                {
                    name : '管理员',
                    href : '#',
                },
                {
                    name : '产品管理',
                    href : '#',
                },
                {
                    name : '产品分类',
                    href : '#',
                }
            ],

            query_info : {

                page : 1,

                per_page : 20,

            },
            
            search_info : {

                page : 1
                
            },                      //分页信息

            table_loading : false,      //表格更新时的loading

            show_modal : false,         //弹框的控制

            super_categories : {},       //产品分类类别

            product_categories : {},     //产品分类列表

            category_detail : {},        //产品分类详情


         }
    },

    mounted () {

        this.fetchCreateInfo();

        this.$on('edit',this.getCategoryDetail);
        
    },

    computed: {
        ...mapGetters('userToken',[
            'getToken'
        ])  
    },

    methods: {

        ...mapMutations('spinShow',[
            'showSpin',
            'closeSpin'
        ]),

         /**
         * 切换tab
         * @param  {tab_name} tab_name {tab的name}
         * @return {undefined} 
         */
        changeTab(tab_name) {
            
            if( tab_name === '查看' ) {

                this.fetchCategoryList(this.query_info);

            }else {

                this.product_categories.data = [];

            }

        },

        /**
         * 页码改变
         * @param  {type} pageNumber {当前页码}
         * @return {undefined} 
         */
        pageChange(pageNumber) {

            this.search_info.page = pageNumber;

            this.search_info.per_page = this.query_info.per_page;

            this.fetchCategoryList(this.search_info);
        },


        /**
         * 每页显示数改变
         * @param  {type} per_page {当前每页显示数}
         * @return {undefined}
         */
        perPageChange(per_page) {

            this.search_info.per_page = per_page;

            this.query_info.per_page = per_page;

            this.fetchCategoryList(this.search_info);

        },

        /**
         * 查看产品分类详情
         * @param  {array} _array {产品分类数据数组 }
         * @return {undefined}
         */
        getCategoryDetail(_array) {

                //父分类数组索引： 0表示id, 1表示说明is_top

            if ( String(_array[1]) === 'is_top' ) {

                this.category_detail = this.product_categories.data.filter((category) => category.id === _array[0])[0];

            } else {

                //子分类数组索引： 0表示自己的id  1表示不是父类的说明is_not_top, 2表示父id

                let product_category = this.product_categories.data.filter((category) => category.id === _array[2])[0].get_sub_categories;

                this.category_detail =  product_category.filter((category) => category.id === _array[0])[0];

            }

            this.show_modal = true;

        },

        /**
         * 更新产品分类信息
         * @param  {string} id {分类id}
         * @return {undefined}
         */
        updateCategory(id,param){

            this.showSpin('请稍后');

            this.$http.post( API_LIST.PRODUCT_CATEGORY + '/' + id, param )
                .then(({ data })=>{
                            
                    if  ( parseInt(data.code) !== 0 )throw new Error(data.error);

                    this.$Message.success('更新成功！');

                    this.show_modal = false;

                    this.fetchCategoryList(this.search_info);
                            
                })
                .catch((err)=>{

                    this.$Message.error(err.message || err.statusText);
            
                })
                .then( this.closeSpin );

        },

        /**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
        // confirmSearch(param) {

        //     this.query_info.name = param.name;

        //     this.query_info.priority = param.priority;

        //     this.search_info = JSON.parse(JSON.stringify(this.query_info));

        //     this.fetchCategoryList(this.query_info);

        // },


        /**
         * 删除产品分类
         * @param  {string} id {需要删除分类的id}
         * @return {undefined}
         */
        deleteCategory(id){

            this.$Modal.confirm({
                title: '确定要删除该产品分类吗？',
                onOk: () => {

                    const param = {
                        _method : 'DELETE'
                    }

                    this.table_loading = true;

                    this.$http.post( API_LIST.PRODUCT_CATEGORY + '/' + id , param )
                        .then(({ data })=>{
                                    
                            if( parseInt(data.code) !== 0 )throw new Error(data.error);
                          
                            this.$Message.success('删除成功');

                            this.fetchCategoryList(this.search_info);
                                    
                        })
                        .catch((err)=>{
                    
                            this.$Message.error(err.message || err.statusText);

                        })
                        .then(() => this.table_loading = false)
                    
                },
                onCancel: () => {}
            });

        },


         /**
         * 新增分类的post数据
         * @return {undefined}
         */
        postData(param){

            this.showSpin('请稍后');

            this.$http.post( API_LIST.PRODUCT_CATEGORY , param )
            
                    .then(({ data })=>{
                                
                        if( parseInt(data.code) !== 0 )throw new Error(data.error);

                        this.$Message.success('创建分类成功！');

                        this.$refs.create.handleReset('formValidate');

                        this.fetchCreateInfo();
                                
                    })
                    
                    .catch((err)=>{

                        this.$Message.error(err.message);
                
                    })

                    .then( this.closeSpin )

        },

         /**
         * 获取创建分类所需信息
         * @return {undefined}
         */

        fetchCreateInfo(){

            this.$http.get( API_LIST.PRODUCT_CATEGORY  + '/create' )
                .then(({ data })=>{
                            
                    if( parseInt(data.code) !== 0 )throw new Error(data.error);

                    this.super_categories = data.super_categories;
                            
                })
                .catch((err)=>{
            
                })

        },

         /**
         * 获取产品分类列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
        fetchCategoryList(param){

            this.table_loading = true;

            let query_str = qs.stringify(param);

            this.$http.get( API_LIST.PRODUCT_CATEGORY + '?' + query_str )
                .then(({ data })=>{
                            
                    if( parseInt(data.code) !== 0 )throw new Error(data.error);
                    
                    this.product_categories = data.product_categories;
                                         
                })
                .catch((err)=>{
            
                    this.$Message.error(err.message);

                })
                .then(() => this.table_loading = false)

        }


     }
 }
 </script>
